package main

import (
	"net/http"
	"strconv"

	"github.com/PuerkitoBio/goquery"
	"qiniupkg.com/x/errors.v7"
)

type ProxyType int

const (
	urlCNProxy            = "http://cn-proxy.com/"
	quickProxy            = "http://www.cnproxy.com/proxy1.html"
	HTTP_PROXY  ProxyType = iota
	HTTPS_PROXY
	SOCKS4
	SOCKS5
)

// Server 代理服务器
type Server struct {
	Host string
	Port int
	Type ProxyType
}

// Capture 获取代理IP接口
type Capture interface {
	Init() error
	HasNext() bool
	Next() *Server
	Reload() error
}

// CNProxyAdapter http://cn-proxy.com/
type CNProxyAdapter struct {
	cur     int
	servers []*Server
}

//Init 初始化
func (cnp *CNProxyAdapter) Init() error {
	if cnp.servers != nil {
		return errors.New("已初始化")
	}
	req, err := http.NewRequest("GET", urlCNProxy, nil)
	if err != nil {
		return err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return err
	}
	rows := doc.Find("tbody tr")
	size := rows.Size()
	cnp.servers = make([]*Server, size)
	for i := 0; i < size; i++ {
		row := rows.Eq(i).Children()
		host := row.Eq(0).Text()
		portS := row.Eq(1).Text()
		port, _ := strconv.Atoi(portS)
		cnp.servers[i] = &Server{Host:host, Port:port, Type:HTTP_PROXY}

	}
	return nil
}

// Reload 重新加载
func (cnp *CNProxyAdapter) Reload() error {
	cnp.servers = nil
	if err := cnp.Init(); err != nil {
		return err
	}
	cnp.cur = 0
	return nil
}

// HasNext 是否存在下一个
func (cnp *CNProxyAdapter) HasNext() bool {
	if cnp.servers == nil {
		return false
	}
	return cnp.cur < len(cnp.servers)
}

// Next 下一个
func (cnp *CNProxyAdapter) Next() *Server {
	if cnp.servers == nil || len(cnp.servers) == cnp.cur {
		return nil
	}
	cur := cnp.cur
	cnp.cur++
	return cnp.servers[cur]
}

//QuickAdapter http://www.kuaidaili.com/
type QuickAdapter struct {
	//当前页码
	currentPage int
	//最大页码
	maxPage int
	//游标
	cur   int
	cache []*Server
}

func (qa *QuickAdapter) Init() error {
	return nil
}
func (qa *QuickAdapter) load(page uint) (*http.Response, error) {
	return nil, nil
}
func (qa *QuickAdapter) Reset() error {
	return nil
}
func (qa *QuickAdapter) HasNext() bool {
	return false
}
func (qa *QuickAdapter) Next() *Server {
	return nil
}
